<template>
  <div class="orderview">
    <template v-for="(order, orderIndex) in orders" :key="orderIndex">
      <OrderTable>
	<template v-for="(item, itemIndex) in order.items" :key="itemIndex">
	  <OrderItem :goodsid="item.goodsid" :count="item.goodsCount"/>
	</template>

	<template #footer>
	  <li v-if="!order.paid">
	    <button @click="togglePay(order, orderIndex as number)">确认支付</button>
	    <button @click="toggleCancel(order, orderIndex as number)">取消订单</button>
	  </li>

	  <li v-else>
	    <button disabled> 已支付 </button>
	  </li>
	</template>
      </OrderTable>
    </template>
  </div>
</template>

<script lang="ts" setup>
 import {OrderTable, OrderItem} from '@/components/Order'
import { currentUser, findMatchOrder, updateOrder, deleteOrder } from '@/service';
import { onMounted, ref } from 'vue';

 const orders = ref<Order[]>([])

 async function togglePay(order: Order, index: number) {
   alert('支付成功')
   order.paid = true
   await updateOrder(order)

   orders.value[index].paid = true
 }

 async function toggleCancel(order: Order, index: number) {
   await deleteOrder(order.id!)

   orders.value.splice(index, 1)
 }

 onMounted(async () => {
   let {data} = await findMatchOrder(await currentUser());
   orders.value = data
 })
</script>